package com.ruike.alisurface;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.ArrayMap;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.ruike.alisurface.bean.lockBean;
import com.ruike.alisurface.https.AppUpdateHttp;
import com.ruike.alisurface.https.MchApiHttp;
import com.ruike.alisurface.serialport.MsgEventBus;
import com.ruike.alisurface.serialport.ShopInfoUtils;
import com.ruike.alisurface.serialport.Ttys3Utils;
import com.ruike.alisurface.serialport.serial.SerialPortInstructUtils;
import com.ruike.alisurface.service.MyFileImgService;
import com.ruike.alisurface.service.MyFileVideoService;
import com.ruike.alisurface.service.MyScrennService;
import com.ruike.alisurface.ui.ShopMain_Aty;
import com.ruike.alisurface.ui.adv.Adv_Aty;
import com.ruike.alisurface.utils.AlogHttpUtils;
import com.ruike.alisurface.utils.FinalDbUtils;
import com.ruike.alisurface.utils.GsonUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_mqtt.MqttConstant;
import com.voodoo.lib_mqtt.MqttOperation;
import com.voodoo.lib_mqtt.MqttService;
import com.voodoo.lib_mqtt.listener.MqttTopicMessageListener;
import com.voodoo.lib_utils.DeviceUtils;
import com.voodoo.lib_utils.SharedUtils;
import com.voodoo.serialport.util.ByteUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.ruike.alisurface.utils.ShareKey.SERVICE_TEL;

public class MqttMessageUtils implements MqttTopicMessageListener, ApiListener, Ttys3Utils.OnSerialPortResultDataListener {

    static volatile MqttMessageUtils messageUtils;

    public static MqttMessageUtils getInstance() {
        if (messageUtils == null) {
            synchronized (MqttOperation.class) {
                if (messageUtils == null) {
                    messageUtils = new MqttMessageUtils();
                }
            }
        }
        return messageUtils;
    }

    public MqttMessageUtils() {
        Ttys3Utils.getInstance().setOnSerialPortResultDataListener(this);
    }

    public void sendIccidInfo() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String sn = DeviceUtils.getDeviceSn();
                String iccid = DeviceUtils.getSimSerialNumber(AppApplication.getAppContext());
                HashMap<String, String> coflist = ShopInfoUtils.getInstance().BzVersion();
                coflist.put("iccid", iccid + "");
                coflist.put("sn", sn);
                String data = GsonUtils.toJson(coflist);
                L.i("mqtt-发送sn 及iccid--" + data);
                MqttService.sendMessage("rkt/mch/savesim/", data);
            }
        }, 20000);
    }


    @Override
    public void processMsg(String topic, String message) {
        L.i("Mqtt收到服务器消息", "主题名称：" + topic, "接收消息：" + message);
        if (topic.equals(MqttConstant.SUBSCR_LANE_UPDATA)) { // 货道更新
            EventBus.getDefault().post(new MsgEventBus("货道更新", "货道更新"));
            return;
        }


        JSONObject bodyJson = null;
        try {
            bodyJson = new JSONObject(message);
            if (topic.equals("rkt/p2p/GID_MCH@@@" + DeviceUtils.getDeviceSn() + "/")) {//登录后台
                L.i("登录后台");
                if (bodyJson.getString("action").equals("login")) {
                    String uid = bodyJson.getString("uid");
                    SharedUtils.getInstance().putString(ShareKey.UID, uid);
                    String token = bodyJson.getString("token");
                    SharedUtils.getInstance().putString(ShareKey.TOKEN, token);

                    EventBus.getDefault().post(new MsgEventBus(MsgEventBus.Jumpbacktothebackground, message));
                } else if (bodyJson.getString("action").equals("ref")) {

                    L.i("MsgEventBus.upDataInquiryorder==" + MsgEventBus.upDataInquiryorder);
                    EventBus.getDefault().post(new MsgEventBus(MsgEventBus.upDataInquiryorder, bodyJson.getString("order_id")));//通知更新问诊订单信息
                }
                return;
            }

            if (topic.equals(MqttConstant.SUBSCR_OUT_GOODS)) { // 远程出货
                if (Constant.isShopShipment || Constant.isTemperature_control) {
                    L.i("isShopShipment" + "已经在出货了，不可出货");
                    return;
                }
                ShopInfoUtils.getInstance().setSlotCallBacK(null);
                getRemoteShipment(bodyJson);
                return;
            }
            if (topic.equals(MqttConstant.SERVICE_TEL)) { //  更新机主电话
                String sn = bodyJson.optString("sn");
                if (sn.equals(DeviceUtils.getDeviceSn())) {
                    String service_tel = bodyJson.optString("service_tel");
                    if (!service_tel.equals("null") && service_tel != null && !service_tel.isEmpty()) {
                        L.i("===service_tel==" + service_tel);
                        SharedUtils.getInstance().putString(SERVICE_TEL, service_tel);
                    } else {
                        SharedUtils.getInstance().putString(SERVICE_TEL, AppApplication.getAppContext().getString(R.string.noPhoneStr));
                    }
                    EventBus.getDefault().post(new MsgEventBus(SERVICE_TEL, service_tel));
                }
                return;
            }


            if (topic.equals(MqttConstant.SUBSCR_OUTADV)) { // 售货机接收广告推送
                UploadAdv(bodyJson);
                return;
            }

            if (topic.equals(MqttConstant.SUBSCR_TEMPERATURE_CONTROL)) { // 温度灯光控制
                if (Constant.isShopShipment || Constant.isTemperature_control) {
                    L.i("isShopShipment" + "已经在出货了，不可出货");
                    return;
                }
                getTemperature_Light(bodyJson);
                return;
            }
            if (topic.equals(MqttConstant.SLOTSET)) { // 售货机接收 推板设置转动信息
                if (Constant.isShopShipment) {
                    L.i("isShopShipment" + "有指令在发送 无法进行设置");
                    return;
                }

                setslotTimes(bodyJson);
                return;
            }
            getSUBSCR_CMD(bodyJson);
            if (topic.equals(MqttConstant.SUBSCR_LOCK)) { //
                sendDoor(bodyJson);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void UploadAdv(JSONObject jsonobject) {

        try {
            String ad_id = jsonobject.getString("ad_id");

            int ad_type = jsonobject.getInt("ad_type"); // 广告类型 0图片 1视频
            String r_list = jsonobject.getString("r_list"); // 数据列表
            SharedUtils.getInstance().putInt(Constant.AdvType.ADV_TYPE_KEY, ad_type);
            if (ActivityUtils.getTopActivity() instanceof ShopMain_Aty) {

                EventBus.getDefault().post(new MsgEventBus("adv_type", "跳转广告页"));

            } else if (ActivityUtils.getTopActivity() instanceof Adv_Aty) {
                if (ad_type == 2) {
                    EventBus.getDefault().post(new MsgEventBus("adv_type", "无广告"));
                    AppUpdateHttp.getConfirm_ApplyAd(ad_id, this);
                    return;
                }
            }
            JSONArray jsonArray = new JSONArray(r_list);
            ArrayList<String> urlList = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                urlList.add(jsonArray.getJSONObject(i).getString("url"));
            }
            Intent intent;
            switch (ad_type) {
                case 0:
                    intent = new Intent(AppApplication.getAppContext(), MyFileImgService.class);
                    intent.putStringArrayListExtra("urlList", urlList);
                    AppApplication.getAppContext().startService(intent);
                    break;

                case 1:
                    intent = new Intent(AppApplication.getAppContext(), MyFileVideoService.class);
                    intent.putStringArrayListExtra("urlList", urlList);
                    AppApplication.getAppContext().startService(intent);
                    break;
                case 2:
                    break;

                default:
                    break;
            }
            AppUpdateHttp.getConfirm_ApplyAd(ad_id, this);

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }


    private String oid_id = "-1";

    /**
     * 远程出货
     *
     * @param bodyJson
     */
    public void getRemoteShipment(JSONObject bodyJson) {
        JSONObject jsonobject = bodyJson;
        String oid = null;
        try {
            oid = jsonobject.getString("oid");

            if (oid_id.equals(oid)) {
                L.i("远程出货oid 相同 ----oid:" + oid, "-----oid_id:" + oid_id);
                return;
            }
            String ot = jsonobject.getString("ot");//远程出货的 出货方式 例如是购买出货  兑换码出货
            String od = jsonobject.getString("od");//订单货道信息
            if (ot.equals("202") || ot.equals("204")) {
                int countNum = 0;
                oid_id = oid;
                Constant.isShopShipment = true;
                if (od.contains("|")) {
                    String[] d = od.split("\\|");
                    for (int i = 0; i < d.length; i++) {
                        String data = d[i];
                        if (data.length() == 6) {
                            doSlotData(data);
                        } else {
                            L.i(" 接收的数据出现错误 " + d);
                        }
                    }
                } else {
                    doSlotData(od);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {

            Constant.isShopShipment = false;
        }
    }

    /**
     * 出货数据的解析
     *
     * @param data
     */
    public void doSlotData(String data) {
        String index = data.substring(0, 3);
        String num = data.substring(3, 5);
        String type = data.substring(5, 6);
        int number = Integer.parseInt(num);
        L.i("远程出货", "----index:" + index + "-----num:" + num + "-----type:" + type);
        ShopInfoUtils.getInstance().TodoShipmentSlot(Integer.parseInt(index), Integer.parseInt(type), number);
    }

    /**
     * 远程获取日志 或截屏信息
     */

    public void getSUBSCR_CMD(JSONObject bodyJson) {
        if (bodyJson.optString("action").equals("pulllog")) {
            String begin = bodyJson.optString("begin");
            String end = bodyJson.optString("end");
            L.i("messageArrived: 上传日志" + begin + "--" + end);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    AlogHttpUtils.upodataLog(begin, end);
                }
            }).start();

        } else if (bodyJson.optString("action").equals("screenshots")) {

            L.i(" 截图 screenshots");
            SharedUtils.getInstance().putString("cmd_id", bodyJson.optString("cmd_id"));
            Intent intent = new Intent(AppApplication.getAppContext(), MyScrennService.class);
            AppApplication.getAppContext().startService(intent);

        }
    }


    /**
     * 开锁
     *
     * @param bodyJson
     */
    public void sendDoor(JSONObject bodyJson) {

        L.i(" 解析开锁mqtt 信息");
        try {
            int ElecEn = bodyJson.getInt("ElecEn");
            int ElecNum = bodyJson.getInt("ElecNum");
            int ElecOnTi = bodyJson.getInt("ElecOnTi");
            int ElecState = bodyJson.getInt("ElecState");
            int boxno = bodyJson.getInt("boxno");
            String msgid = bodyJson.getString("msgid");
            L.i("msgid", msgid, "boxno", boxno);
//            ShareUtils.getInstance().putString(LOCK_MSGID, msgid);

            List<lockBean> locklist = FinalDbUtils.getInstance().findAllByWhere(lockBean.class, " boxno = " + boxno);
            if (locklist != null && locklist.size() > 0) {
                locklist.get(0).setMsgid(msgid);
                FinalDbUtils.getInstance().update(locklist.get(0));
            } else {
                lockBean lockBean = new lockBean();
                lockBean.setBoxno(boxno);
                lockBean.setMsgid(msgid);
                FinalDbUtils.getInstance().save(lockBean);
            }
            Ttys3Utils.getInstance().DoorSetting(boxno, ElecOnTi, ElecNum);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //==============================================================上传指令的返回值


    /**
     * 发送开启电控锁 返回值
     * Topic:rkt/lockrespond/
     * {"msgid":"01234567890123456789_lock","lockinit": 2,"doorinit": 2,"locknow": 2,"doornow": 2}
     *
     * @param date
     * @return
     */
    public void LockOpenDoor(String date) {
        String[] data_code = date.split(" ");
        if (data_code.length < 8) {
            L.i("发送电控锁 数据失败  ，数据不完整");
            return;
        }
        int lockinit = Integer.parseInt(data_code[3]);
        int doorinit = Integer.parseInt(data_code[4]);
        int locknow = Integer.parseInt(data_code[5]);//，1-关闭，2-开启
        int doornow = Integer.parseInt(data_code[6]);//，1-关闭，2-开启

        int opendoor = Integer.parseInt(data_code[7]);//00-IC2主柜
        int locktype = Integer.parseInt(data_code[8]);// 00-机械开锁，01-电控开锁

        HashMap<String, Object> map = new HashMap<>();

        if (locktype == 1) {
            List<lockBean> locklist = FinalDbUtils.getInstance().findAllByWhere(lockBean.class, " boxno = " + opendoor);
            if (locklist != null && locklist.size() > 0) {
                map.put("msgid", locklist.get(0).getMsgid());
                map.put("lockinit", lockinit);
                map.put("doorinit", doorinit);
            }
        }
        map.put("sn", DeviceUtils.getDeviceSn());
        map.put("locknow", locknow);
        map.put("doornow", doornow);
        map.put("boxno", opendoor);
        map.put("opentype", locktype);
        String data = GsonUtils.toJson(map);
        L.i(" 发送电控锁 上传数据===" + data);
        if (locknow == 2) {
//            Topic:rkt/lockrespond/
//{"msgid":"01234567890123456789_lock","sn":"999999999","lockinit": 2,"doorinit": 2,"locknow": 2,"doornow": 2,"boxno":0}
            MqttService.sendMessage("rkt/lockrespond/", data);
        }

    }

    /**
     * 发送关闭电控锁 返回值
     * Topic:rkt/lockrespond/
     * {"msgid":"01234567890123456789_lock","lockinit": 2,"doorinit": 2,"locknow": 2,"doornow": 2}
     *
     * @param date
     * @return
     */
    public void LockCloseDoor(String date) {
        String[] data_code = date.split(" ");
        if (data_code.length < 6) {
            L.i("上传 关闭电控锁 数据失败  ，数据不完整");
            return;
        }
        int locknow = Integer.parseInt(data_code[3]);//，1-关闭，2-开启
        int doornow = Integer.parseInt(data_code[4]);//，1-关闭，2-开启

        int opendoor = Integer.parseInt(data_code[5]);//00-IC2主柜
        int locktype = Integer.parseInt(data_code[6]);// 00-机械关锁，01-电控关锁

        HashMap<String, Object> map = new HashMap<>();

        List<lockBean> locklist = null;
        if (locktype == 1) {
            locklist = FinalDbUtils.getInstance().findAllByWhere(lockBean.class, " boxno = " + opendoor);
            if (locklist != null && locklist.size() > 0) {
                map.put("msgid", locklist.get(0).getMsgid());
            }
        }
        map.put("sn", DeviceUtils.getDeviceSn());
        map.put("locknow", locknow);
        map.put("doornow", doornow);
        map.put("boxno", opendoor);
        map.put("opentype", locktype);

        String data = GsonUtils.toJson(map);
        L.i(" 发送电控锁 上传数据===" + data);

        if (locknow == 1) {  //关闭
//            Topic:rkt/closelockrespond/
//                    {"msgid":"01234567890123456789_lock","sn":"999999999","lockclose": 2,"doorclose": 2,"boxno":0,"opentype":1}
            MqttService.sendMessage("rkt/closelockrespond/", data);
        }
        if (locktype == 1) {
            if (locklist != null && locklist.size() > 0) {
                L.i(" locklist  删除msgid ");
                FinalDbUtils.getInstance().delete(locklist.get(0));
            }
        }
    }


    /**
     * 发送后台偷盗指令
     * Topic：rkt/msgrespond/
     * 报文：{
     * "sn":"868821045734076","droptype":"1","dropno":1
     * }
     */
    public void sendSteal(String date) {
        String[] data_code = date.split(" ");
        if (data_code.length < 3) {
            L.i("上传偷盗指令 数据失败  ，数据不完整");
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        int dropno = Integer.parseInt(data_code[3]);//，1-关闭，2-开启
        map.put("sn", DeviceUtils.getDeviceSn());
        map.put("dropno", dropno);
        map.put("droptype", "1");
        String data = GsonUtils.toJson(map);
        MqttService.sendMessage("rkt/msgrespond/", data);
    }

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {

    }

    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {

    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {

    }

    /**
     * 上传温湿度信息
     */
    public void Beat() {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                try {
//                    MchApiHttp.getSignal_Intensity(baseView, NetWorkListenerService.getmSignalStrength());
                } catch (Exception e) {
                    L.i("mqtt 上传网络信号异常 ");
                }
                L.i("mqtt: 是否开始温度信息查询isShopShipment =" + Constant.isShopShipment + "--mqtt 在线状态--" + MqttService.isConnected());

                if (!Constant.isShopShipment && !Constant.isTemperature_control) {
                    handler.removeCallbacksAndMessages(null);
                    handler.sendEmptyMessage(5);
                }
            }
        };
        timer.schedule(timerTask, 10, 250000);
    }

    /**
     * 上传信号值信息
     */
    public void sendNetInfo() {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                try {
                    MchApiHttp.getSignal_Intensity(SharedUtils.getInstance().getInt(ShareKey.SIGNALVALUE), new ApiListener() {
                        @Override
                        public void onRequestStart(String requestUrl, int requestId) {
                            L.i("上传信号值信息 ==" + requestUrl);
                        }

                        @Override
                        public void onRequestComplete(String requestUrl, int requestId) {

                        }

                        @Override
                        public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
                            L.i("信号上传成功");
                        }

                        @Override
                        public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {
                            L.i("信号上传失败");
                        }
                    });
                } catch (Exception e) {
                    L.i("上传信号值信息 异常 ");
                }

            }
        };
        timer.schedule(timerTask, 1100, 240000);
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (Constant.isShopShipment || Constant.isTemperature_control) {

                return;
            }
            switch (msg.what) {
                case 1:
                    Ttys3Utils.getInstance().getWenKongVersion(3);
                    break;
                case 2:
                    Ttys3Utils.getInstance().getWenKongVersion(4);
                    break;
                case 3:
                    Ttys3Utils.getInstance().getWenKongVersion(5);
                    break;
                case 4:
                    wkresultBNum = 0;
                    if (uploadHeardData == null) {
                        L.i("mqtt  ", "上传温控信息==数据为null 无法上传");
                        return;
                    }
                    if (uploadHeardData.contains("null")) {
                        L.i("mqtt  ", "上传温控信息==数据有null 无法上传");
                        return;
                    }
                    uploadHeardData = uploadHeardData.replaceAll(" ", "");
                    L.i("mqtt  ", "上传温控信息==" + uploadHeardData);
                    String sendmsg = "{\"temid\": \"" + DeviceUtils.getDeviceSn() + "\"," + "\"temhum\": \"" + uploadHeardData + "\"" + "}";
                    MqttService.sendMessage("rkt/mch/heart/", sendmsg);

                    break;
                case 5:
                    Ttys3Utils.getInstance().sendHexData(SerialPortInstructUtils.checkhumidity());
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            L.i("mqtt  ", "上传温控信息==湿度信息没有返回 开始温度查询");
                            humidity = 0;
                            handler.sendEmptyMessageDelayed(1, 500);
                        }
                    }, 3000);
                    break;
            }
        }
    };

    /**
     * 串口返回数据
     *
     * @param resultDataStr 返回的String类型的数据
     * @param resultBytes   返回的数组类型的数据
     */
    String uploadHeardData;
    int humidity;
    boolean isHumidifier = true;
    int wkresultBNum = 0;

    public void onDataReceived(String resultDataStr, byte[] resultBytes) {
        L.i("返回的数据：" + resultDataStr);
        if (resultBytes.length < 4) {
            L.e("返回指令异常：" + resultDataStr);
            return;
        }

        if (resultBytes[0] == (byte) 0x23) {  // 温控等
            switch (resultBytes[2]) {
                case 0x01: // 温湿度
//                  23 03 03 03 2C ==> 23 11 01 00 03 [01] (16) 03 01 19 03 01 19 01 16 03 03 03 A9 [温度正负，2为负](温度值 16进制)
                    int symbol = Integer.parseInt(ByteUtils.byteToHex(resultBytes[5]), 16); // 温度正负值，2为零下
                    int temperature = Integer.parseInt(ByteUtils.byteToHex(resultBytes[6]), 16); // 温度值
                    int currentTemperature = temperature * (symbol == 2 ? -1 : 1); // 将当前温度设置为正负值
                    L.i("当前温度：" + currentTemperature);
                    SharedUtils.getInstance().putInt(ShareKey.TEMPERATURE, currentTemperature);
                    EventBus.getDefault().post(new MsgEventBus("温度值", currentTemperature + ""));
                    resultBytes[3] = (byte) humidity;
                    uploadHeardData = ByteUtils.byteArrToHex(resultBytes, 2, resultBytes.length - 1);
                    wkresultBNum = 1;
                    handler.sendEmptyMessageDelayed(2, 500);
                    break;
                case 0x02: // 继电器
//                  23 03 03 04 2D ==> 23 08 02 00 01 00 01 00 01 30
                    wkresultBNum = 2;
                    uploadHeardData = uploadHeardData + " " + ByteUtils.byteArrToHex(resultBytes, 2, resultBytes.length - 1);
                    handler.sendEmptyMessageDelayed(3, 500);
                    break;
                case 0x03: // 运行类型
//                  23 03 03 05 2E ==> 23 03 03 02 2B
                    if (wkresultBNum == 2) {
                        uploadHeardData = uploadHeardData + " " + ByteUtils.byteArrToHex(resultBytes, 2, resultBytes.length - 1);
                        handler.sendEmptyMessageDelayed(4, 500);
                    }
                    break;
                case 0x06: // 查询温控板返回
//                  23 03 03 06 2F ==> 23 08 06 14 08 04 14 04 07 70
                    String T = new StringBuffer()
                            .append(ByteUtils.byteToHex(resultBytes[3]))
                            .append(ByteUtils.byteToHex(resultBytes[4]))
                            .append(ByteUtils.byteToHex(resultBytes[5]))
                            .append(ByteUtils.byteToHex(resultBytes[6]))
                            .append(ByteUtils.byteToHex(resultBytes[7]))
                            .append(ByteUtils.byteToHex(resultBytes[8]))
                            .toString();
                    SharedUtils.getInstance().putString("T", T);
//                    if (onOperationStatesListener != null) {
//                        onOperationStatesListener.onShowMessage("温控板子信息查询完成");
//                    }
                    break;
            }
        } else {

            if (resultBytes[2] == (byte) 0x02) {
                L.i("IC2 串口3  出货完成指令===" + resultDataStr);
                if (ShopInfoUtils.getInstance().slotCallBacK != null) {
                    ShopInfoUtils.getInstance().slotCallBacK.onSlotSuccess(resultDataStr, resultBytes);
                }
                return;
            }

            if (resultBytes[1] == (byte) 0x08 && resultBytes[2] == (byte) 0x04) {
                L.i("IC2 串口3  电控锁开门指令===" + resultDataStr);
                LockOpenDoor(resultDataStr);
                return;
            }
            if (resultBytes[1] == (byte) 0x06 && resultBytes[2] == (byte) 0x1F) {
                L.i("IC2 串口3  电控锁关门指令===" + resultDataStr);
                LockCloseDoor(resultDataStr);
                return;
            }

            if (resultBytes[1] == (byte) 0x05 && resultBytes[2] == (byte) 0x1E) {
                L.i("IC2 串口3  偷盗指令===" + resultDataStr);
                sendSteal(resultDataStr);
                return;
            }
            //地址码	功能码	返回有效字节数	 湿度值	  温度值 	低位 高位校验码
            // 01         03       04            01 D0    01 21      3B    BE
            if (resultBytes[1] == (byte) 0x03 && resultBytes[2] == (byte) 0x04) {
                handler.removeCallbacksAndMessages(null);
                String data[] = resultDataStr.split(" ");
                humidity = ByteUtils.HexToInt(data[3] + data[4]) / 10;
//            float wd= (float) (ByteUtils.HexToInt(data[5] + data[6]) / 10);\
                SharedUtils.getInstance().putInt(ShareKey.HUMIDITY, humidity);
                EventBus.getDefault().post(new MsgEventBus("湿度值", humidity + ""));
                L.i("IC2 串口3  湿度 值=isHumidifier==" + isHumidifier, humidity);
                int humiset_min = SharedUtils.getInstance().getInt("humiset_min", 0);
                int humiset_max = SharedUtils.getInstance().getInt("humiset_max", 0);
                int humisetTime = SharedUtils.getInstance().getInt("humisetTime", 0);

                if (humiset_max < humidity && !isHumidifier) {
                    isHumidifier = true;
                    L.i("IC2 串口3  湿度 值===达到指定湿度 关闭湿度器");
                    Ttys3Utils.getInstance().isHumidifier(false);
                }
                if (humiset_min > humidity && isHumidifier) {
                    isHumidifier = false;
                    L.i("IC2 串口3  湿度 值===未达到指定湿度 开启湿度器");
                    Ttys3Utils.getInstance().isHumidifier(true);
                }

                handler.sendEmptyMessageDelayed(1, 1500);
            }
            if (resultBytes[2] == 0x06) {
                // 10 02 06 18 单片机接到普通LED命令成功返回
                L.v(new StringBuffer("当前测试 设置灯光 完成"));
            }
            // 10 09 1D 00 13 0B 1D 13 0C 05 95 查询驱动板返回
            if (resultBytes[2] == 0x1D) {
                String mv = new StringBuffer()
                        .append(ByteUtils.byteToHex(resultBytes[4]))
                        .append(ByteUtils.byteToHex(resultBytes[5]))
                        .append(ByteUtils.byteToHex(resultBytes[6]))
                        .append(ByteUtils.byteToHex(resultBytes[7]))
                        .append(ByteUtils.byteToHex(resultBytes[8]))
                        .append(ByteUtils.byteToHex(resultBytes[9]))
                        .toString();
                SharedUtils.getInstance().putString("MV", mv);
                L.i(new StringBuffer("驱动板信息==").append(mv));
              /*  if (onOperationStatesListener != null) {
                    onOperationStatesListener.onShowMessage("驱动板信息查询完成");
                }*/
            }
            if (resultBytes[2] == (byte) 0x21) {
                ArrayMap<String, Object> map = new ArrayMap<>();
                map.put("t_id", t_id);
                map.put("cmd", resultDataStr.replaceAll(" ", ""));
                MqttService.sendMessage(MqttConstant.SLOTSET_S, GsonUtils.toJson(map));
                L.i("每层的时间设置返回==");
                EventBus.getDefault().post(new MsgEventBus("每层的设置返回", resultDataStr));
                return;
            }

            if (resultBytes[2] == (byte) 0x23) {
                ArrayMap<String, Object> map = new ArrayMap<>();
                map.put("t_id", t_id);
                map.put("cmd", resultDataStr.replaceAll(" ", ""));
                MqttService.sendMessage(MqttConstant.SLOTSET_S, GsonUtils.toJson(map));
                L.i("保存所有的时间设置返回==");
                EventBus.getDefault().post(new MsgEventBus("保存所有的设置返回", resultDataStr));
            }
        }
    }

    public void SerialsleepTime(int tiems, byte cabinet, byte[] data) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Ttys3Utils.getInstance().sendHexData(
                        SerialPortInstructUtils.temperatureControls(cabinet, data));
                L.i("温控指令==副柜=" +
                        SerialPortInstructUtils.temperatureControls(cabinet, data));
            }
        }, tiems);


    }

    /**
     * 设置温控及灯
     */
    public void getTemperature_Light(JSONObject body) {
        try {
            Constant.isTemperature_control = true;
            JSONObject jsonObject = body;
            if (body.toString().contains("temauto")) {
                // :{"msgid":"38a99cfc-a1b8-42d6-af05-6caef7b36498","temauto":"020001000A3C0201010000FF01"}
                String temautoStr = jsonObject.getString("temauto");
                byte[] temautos = ByteUtils.hexToByteArr(temautoStr); // 直接转换成byte数组

                Ttys3Utils.getInstance().sendHexData(
                        SerialPortInstructUtils.temperatureControls((byte) 0x23, temautos));
                L.i("温控指令==主柜=" +
                        SerialPortInstructUtils.temperatureControls((byte) 0x23, temautos));
                SerialsleepTime(300, (byte) 0x24, temautos);

            } else if (body.toString().contains("humiset")) {
                String humiset = jsonObject.getString("humiset");
                int humiset_min = Integer.parseInt(humiset.substring(0, 2), 16);
                int humiset_max = Integer.parseInt(humiset.substring(2, 4), 16);
                int humisetTime = Integer.parseInt(humiset.substring(4, 6), 16);

                SharedUtils.getInstance().putInt("humiset_min", humiset_min);
                SharedUtils.getInstance().putInt("humiset_max", humiset_max);
                SharedUtils.getInstance().putInt("humisetTime", humisetTime);
                Ttys3Utils.getInstance().isHumidifier(true);
                isHumidifier = false;
                L.i("IC2 串口3  湿度 值===开启湿度器", "湿度最小值=" + humiset_min, "湿度最大值=" + humiset_max, "湿度间隔时间=" + humisetTime);
            } else {
                L.i("messageArrived: ----我是灯光指令");
                // : MQTT收到{"msgid":"01234567890123456789","LEDMode":0,"LEDNum":0,"LEDOnOff":1,"LEDMax":0,"LEDTime":1,"LEDstate":1}

                int LEDMode = jsonObject.getInt("LEDMode");
                int LEDOnOff = jsonObject.getInt("LEDOnOff");
                String LEDMax = jsonObject.getString("LEDMax");
                String LEDTime = jsonObject.getString("LEDTime");
                int LEDstate = jsonObject.getInt("LEDstate");
                int LEDNum = jsonObject.getInt("LEDNum");
                int light = Integer.parseInt(LEDMax);
                int time = Integer.parseInt(LEDTime);
                L.i("当前 灯光：" + (LEDOnOff == 1 ? "开灯" : "关灯"));
                //发送灯光命令
                int timecount = 0;
                for (int i = 10; i < 15; i++) {
                    SerialledOpenOrClose(timecount++, i, LEDMode, LEDNum,
                            LEDOnOff == 1, light, time);
                }
            }
        } catch (
                JSONException e) {
            e.printStackTrace();
        } finally {
            Constant.isTemperature_control = false;
            L.i("       Constant.isTemperature_control===" + Constant.isTemperature_control);
        }
    }

    /**
     * 间隔时间发送开关灯
     *
     * @param i
     * @param LEDMode
     * @param LEDNum
     * @param LEDOnOff
     * @param light
     * @param time
     */
    private void SerialledOpenOrClose(int timecount, int i, int LEDMode, int LEDNum, boolean LEDOnOff, int light, int time) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Ttys3Utils.getInstance().ledOpenOrClose(i, LEDMode, LEDNum, LEDOnOff, light, time);
            }
        }, 300 * timecount);
    }

    String t_id;

    /**
     * 设置推板货道转动时间及保存
     *
     * @param bodyJson
     */
    public void setslotTimes(JSONObject bodyJson) {
        try {
            t_id = bodyJson.getString("t_id");
            String morut = bodyJson.getString("morut");

            Ttys3Utils.getInstance().sendHexData(morut);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
